import asyncio
import threading


task = None


async def async_task():
    count = 0
    while True:
        print(f"协程正在运行 {count}")
        await asyncio.sleep(1)
        count += 1


async def main_test():
    global task
    task = asyncio.create_task(async_task())
    try:
        await task
    except asyncio.CancelledError:
        print("协程被取消")
        task = None
    except Exception as e:
        print(f"发生异常{e}")


def main():
    asyncio.run(main_test())


def input_cmd():
    help_str = """
1.运行协程
2.取消协程
q.退出
"""
    global task
    while True:
        cmd = input(help_str)
        if cmd == "1":
            if task == None:
                t1 = threading.Thread(target=main)
                t1.daemon = True
                t1.start()
            else:
                print("协程正在运行")
        elif cmd == "2":
            task.cancel()
        elif cmd == "q":
            break
        else:
            print("输入错误")


if __name__ == "__main__":
    input_cmd()
